﻿using Bandit.Helpers;
//new
using Bandit.UI;
using Bandit.UI.Controls;
using BenaGo.Helper;
using ETC.DLEDPositionTool.Core;
using ETC.DLEDPositionTool.Helpers;
using ETC.DLEDPositionTool.Models;
using ETC.DLEDPositionTool.Windows;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XWPF.UserModel;
using OpenCvSharp;
using OpenCvSharp.Flann;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Color = System.Windows.Media.Color;
using ColorConverter = System.Windows.Media.ColorConverter;
using ComboBox = System.Windows.Controls.ComboBox;
using ICell = NPOI.SS.UserModel.ICell;

namespace ETC.DLEDPositionTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : BanditWindow
    {
        /// <summary>
        /// 视图模型
        /// </summary>
        public ViewModels.MainViewModel ViewModel { get { return App.MainViewModel; } }

        public BaslerCamcs camera { get; set; } = new BaslerCamcs();

        BeanGoOpenCVHelper beanGoOpenCVHelper = new BeanGoOpenCVHelper();

        FrmPreview frmPreview;
        public MainWindow()
        {
            InitializeComponent();

            TestConfig.LoadConfig(App.GetFilePathOfTestStationConfig());

            this.CurrentShowGrid = this.GridOperator;

            camera.CameraImageEvent += Camera_CameraImageEvent;

            #region Window Loaded

            this.Loaded += delegate
            {
                ViewModel.OnClick = new Bandit.UI.MVVM.CommandHandler(OnClick);

                this.DataContext = ViewModel;

                m_pictureBox = new System.Windows.Forms.PictureBox();
                m_pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;

                pictureBoxHost.Child = m_pictureBox;

                if (camera.CameraNumber > 0)
                {
                    camera.CameraInit();
                    //camera.setExposureTime(100000);
                    camera.setExposureTime(10000);
                    camera.setGainRaw(2);
                    camera.KeepShot();
                }
                else
                {
                    this.ShowPromptWindow("未连接到相机",PromptType.Red);

                }
                //在这里连接USB
                this.InitMiniLedLightUpSerialPort();

                RefreshLightParameter();

                LoadedButtonOnClick();

                this.txtBarcode.Focus();

                UpdateStartButtonState();

                this.WindowState = WindowState.Maximized;
            };

            this.Closed += delegate
            {
                camera.DestroyCamera();
            };

            #endregion

            #region Window KeyDown
            this.KeyDown += (sender, e) =>
            {
                if (e.Key == Key.F5 || e.Key == Key.Enter)
                {
                    //this.StartTest();
                }
            };
            #endregion
        }

        #region OnClick Event

        private void OnClick(object parameter)
        {
            if (parameter != null)
            {
                switch (parameter.ToString())
                {
                    case "StartTest":
                        {
                            this.StartTest();
                        }
                        break;
                    case "StopTest":
                        {
                            this.StopTest();
                        }
                        break;
                    case "ClearRtxtTestData":
                        {
                            this.rtxtTestData.Document.Blocks.Clear();
                        }
                        break;
                    case "CancelLoop":
                        {
                            borderLoop.Visibility = Visibility.Collapsed;
                            ViewModel.TestConfig.IsLoopTest = false;
                            TestConfig.SaveConfig();
                        }
                        break;
                    case "Login":
                        string password = "";

                        #if !DEBUG
                            password = "TPKETC";
                        #endif

                        ViewModel.IsLogin = this.ShowPasswordDialog("Enginess Login", password);
                        if(ViewModel.IsLogin)
                        {
                            ChangePage(this.GridEnginer);
                        }
                        
                        break;
                    case "Logout":
                        ViewModel.IsLogin = false;
                        ChangePage(this.GridOperator);
                        break;
                    case "CloseEnginer":
                        ChangePage(this.GridOperator);
                        break;
                    case "SaveSetting":

                        Core.TestConfig.SaveConfig(App.GetFilePathOfTestStationConfig());

                        ChangePage(this.GridOperator);

                        break;
                    case "PreviewRectROIImage":

                        //string ImagePath = "C:\\Users\\beango.cheng\\Desktop\\2023-04-10_13_23_27_469.bmp";
                        string ImagePath = TestConfig.Instance.ROIImagePath;//"C:\\Users\\beango.cheng\\Desktop\\2.bmp";

                        if (!File.Exists(ImagePath))
                        {
                            //if (!this.CCD.SaveImage(ImagePath))
                            //{
                            this.ShowDialog("不存在文件或保存失败！", "预览失败", MessageBoxButton.OK, DialogIcon.Cry);
                            return;
                            //}
                        }

                        frmPreview = new FrmPreview(ImagePath);

                        frmPreview.Closed += delegate
                        {
                            frmPreview = null;
                        };

                        frmPreview.Show();

                        break;
                    case "Operator":
                        {
                            ChangePage(this.GridOperator);
                        }
                        break;
                    case "TestConfig":
                        {
                            ShowWindow<Windows.FrmConfig>(this);
                        }
                        break;
                    case "Setting":
                        {
                            ShowWindow<Windows.FrmSetting>(this);
                        }
                        break;
                    case "Enginer":
                        ChangePage(this.GridEnginer);
                        break;
                    case "SaveImage":
                        {
                            if (this.tempBitmap != null)
                            {
                                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                                sfd.Filter = "BMP|*.bmp";
                                if (sfd.ShowDialog().Value)
                                {
                                    SaveImage(sfd.FileName);
                                }
                            }
                        }
                        break;
                    case "CheckUpdate":
                        if (!App.CheckUpdate())
                        {
                            this.ShowDialog(App.GetString("NotNeedUpdatePrompt"), App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.OK);
                        }
                        break;
                    case "About":
                        {
                            Windows.FrmAbout.Show(this);
                        }
                        break;
                    case "FadaImage":
                        {
                            ImageShow.Visibility = Visibility.Visible;

                            imgFadaShow.Source = imgCCD1.Source;

                            BalserImageShowName.Visibility = Visibility.Collapsed;
                        }
                        break;
                    case "CloseFadaImage":
                        {
                            BalserImageShowName.Visibility = Visibility.Visible;
                            ImageShow.Visibility = Visibility.Collapsed;
                        }
                        break;

                    #region 点灯机
                    case "DoCMD":
                        {
                            index = 0;

                            this.rtxtTestData.Document.Blocks.Clear();

                            DoCMD();

                        }
                        break;
                    case "AllLight":
                        {
                            this.Loading.Show("Testing...");

                            this.rtxtTestData.Document.Blocks.Clear();

                            Task.Factory.StartNew(() =>
                            {
                                this.ALLLEDLight();

                            }).ContinueWith(t =>
                            {
                                //Thread.Sleep(10000);

                                //DLEDLightingHelper.Instance.PowerOff();

                                this.Loading.Hide();
                            });
                            
                        }
                        break;
                    case "SingleLight":
                        {
                            this.Loading.Show("Testing...");

                            Task.Factory.StartNew(() =>
                            {

                                this.SingleLEDLight();

                            }).ContinueWith(t =>
                            {
                                //Thread.Sleep(10000);

                                //DLEDLightingHelper.Instance.PowerOff();
                                this.Loading.Hide();
                            });
                            
                        }
                        break;
                    case "LoopSingleLedLight":
                        {
                            this.Loading.Show("Testing...");

                            Task.Factory.StartNew(() =>
                            {
                                LoopSingleLEDLight();

                            }).ContinueWith(t =>
                            {
                                //Thread.Sleep(10000);

                                //DLEDLightingHelper.Instance.PowerOff();
                                this.Loading.Hide();
                            });
                            
                        }
                        break;
                    case "LoopSingleICLight":
                        {
                            this.Loading.Show("Testing...");

                            Task.Factory.StartNew(() =>
                            {
                                LoopICLight();

                            }).ContinueWith(t =>
                            {
                                //Thread.Sleep(10000);

                                //DLEDLightingHelper.Instance.PowerOff();
                                this.Loading.Hide();
                            });
                            
                        }
                        break;
                    case "PowerOFF":
                        {
                            this.Loading.Show("Testing...");

                            Task.Factory.StartNew(() =>
                            {
                                DLEDLightingHelper.Instance.PowerOff();

                                index = 0;

                            }).ContinueWith(t =>
                            {
                                this.Loading.Hide();
                            });
                            
                        }
                        break;
                    case "RefreshLightParameter":
                        {
                            RefreshLightParameter();
                        }
                        break;
                    #endregion

                    case "OpenFilePath":
                        {
                            OpenFileDialog openFileDialog = new OpenFileDialog();
                            //openFileDialog.Filter = "Sql 文件(*.sql)|*.sql";
                            //过滤文件类型
                            openFileDialog.Filter = "bmp(*.bmp)|*.bmp|所有文件(*.*)|*.*";

                            //允许多选
                            openFileDialog.Multiselect = true;

                            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                //FileName 完整路径：相对路径+文件名+后缀
                                //文件内容读取
                                string name = openFileDialog.FileName;

                                TestConfig.Instance.ROIImagePath = name;
                            }
                        }
                        break;
                    case "OpenImagePathThreshold":
                        {
                            OpenFileDialog openFileDialog = new OpenFileDialog();
                            //openFileDialog.Filter = "Sql 文件(*.sql)|*.sql";
                            //过滤文件类型
                            openFileDialog.Filter = "bmp(*.bmp)|*.bmp|所有文件(*.*)|*.*";

                            //允许多选
                            //openFileDialog.Multiselect = true;

                            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                //FileName 完整路径：相对路径+文件名+后缀
                                //文件内容读取
                                string name = openFileDialog.FileName;

                                txtImagePathName.Text = name;
                            }
                        }
                        break;
                    case "ThresholdImage":
                        {
                            ThresholdImage();
                        }
                        break;

                    case "FindContoursArea":
                        {
                            FindContoursArea();
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        #endregion

        #region Button OnClick Event
        private void LoadedButtonOnClick()
        {
            //选择所有
            this.btnAllCheck.Click += delegate
            {
                foreach (MyROIRect rect in TestConfig.Instance.ROIRectList)
                {
                    rect.IsEnable = true;
                }
            };
            //选择反选
            this.btnInverseCheck.Click += delegate
            {
                foreach (MyROIRect rect in TestConfig.Instance.ROIRectList)
                {
                    rect.IsEnable = false;
                }
            };
            //重置
            this.btnReset.Click += delegate
            {
                this.ResetRect();

                if (frmPreview != null)
                {

                    frmPreview.Show();
                    frmPreview.ShowImage();

                }
                else
                {
                    string ImagePath = TestConfig.Instance.ROIImagePath;//"C:\\Users\\beango.cheng\\Desktop\\2.bmp";
                    frmPreview = new FrmPreview(ImagePath);
                    frmPreview.CloseFrmPreviewChanged += delegate
                    {
                        frmPreview = null;
                    };
                    frmPreview.Show();
                }
            };
            //选择全选
            this.btnSingleAllCheck.Click += delegate
            {
                foreach (MyROIRect rect in TestConfig.Instance.SingleROIRectList)
                {
                    rect.IsEnable = true;
                }
            };
            //选择反选
            this.btnSingleInverseCheck.Click += delegate
            {
                foreach (MyROIRect rect in TestConfig.Instance.SingleROIRectList)
                {
                    rect.IsEnable = false;
                }
            };
            //重置
            this.btnSingleReset.Click += delegate
            {
                this.ResetSingleRect();

                if (frmPreview != null)
                {

                    frmPreview.Show();
                    frmPreview.ShowImage();

                }
                else
                {
                    string ImagePath = TestConfig.Instance.ROIImagePath;//"C:\\Users\\beango.cheng\\Desktop\\2.bmp";
                    frmPreview = new FrmPreview(ImagePath);
                    frmPreview.CloseFrmPreviewChanged += delegate
                    {
                        frmPreview = null;
                    };
                    frmPreview.Show();
                }
            };
        }

        #endregion

        #region 重置
        private void ResetSingleRect()
        {
            TestConfig.Instance.SingleROIRectList.Clear();

            for (int i = 0; i < TestConfig.Instance.SingleRowsCount; i++)
            {
                for (int j = 0; j < TestConfig.Instance.SingleColsCount; j++)
                {

                    TestConfig.Instance.SingleROIRectList.Add(new MyROIRect
                    {
                        Text = (i * TestConfig.Instance.SingleColsCount + j + 1).ToString(),
                        Name = "Rect_" + (i * TestConfig.Instance.SingleColsCount + j + 1).ToString(),
                        X = TestConfig.Instance.SingleStartPointX + j * TestConfig.Instance.SingleRectWidth + j * TestConfig.Instance.SingleColInterval,
                        Y = TestConfig.Instance.SingleStartPointY + i * TestConfig.Instance.SingleRectHeight + i * TestConfig.Instance.SingleRowInterval,
                        Width = TestConfig.Instance.SingleRectWidth,
                        Height = TestConfig.Instance.SingleRectHeight
                    });

                }
            }


        }

        private void ResetRect()
        {
            TestConfig.Instance.ROIRectList.Clear();

            for (int i = 0; i < TestConfig.Instance.RowsCount; i++)
            {
                for (int j = 0; j < TestConfig.Instance.ColsCount; j++)
                {


                    TestConfig.Instance.ROIRectList.Add(new MyROIRect
                    {
                        Text = (i * TestConfig.Instance.ColsCount + j + 1).ToString(),
                        Name = "Rect_" + (i * TestConfig.Instance.ColsCount + j + 1).ToString(),
                        X = TestConfig.Instance.StartPointX + j * TestConfig.Instance.RectWidth + j * TestConfig.Instance.ColInterval,
                        Y = TestConfig.Instance.StartPointY + i * TestConfig.Instance.RectHeight + i * TestConfig.Instance.RowInterval,
                        Width = TestConfig.Instance.RectWidth,
                        Height = TestConfig.Instance.RectHeight
                    });

                }
            }


        }
        #endregion

        #region 点灯机

        #region 点灯机设置指令
        private void DoCMD()
        {
            this.Loading.Show("Setting...");

            Task.Factory.StartNew(() =>
            {
                if (!this.SetModel())
                {
                    return;
                }

                AppendTestData("PinOSTest", MyBrushes.TESTING);
                if (!ResultRejude(DLEDLightingHelper.Instance.GetPinOSTestData()))
                {
                    AppendTestData("PinOSTest Fail", MyBrushes.Red);
                    return;
                }
                AppendTestData("LEDDriverICStandbyVolCur", MyBrushes.TESTING);
                if (!ResultRejude(DLEDLightingHelper.Instance.GetLEDDriverICStandbyVolCurData()))
                {
                    AppendTestData("LEDDriverICStandbyVolCur Fail", MyBrushes.Red);
                    return;
                }
                AppendTestData("LEDDriverICWorkingVolCur", MyBrushes.TESTING);
                if (!ResultRejude(DLEDLightingHelper.Instance.GetLEDDriverICWorkingVolCurData()))
                {
                    AppendTestData("LEDDriverICWorkingVolCur Fail", MyBrushes.Red);
                    return;
                }
                AppendTestData("全电流测试4000", MyBrushes.TESTING);
                if (!ResultRejude(DLEDLightingHelper.Instance.GetAllLEDTestData(4000)))
                {
                    AppendTestData("全电流测试4000 Fail", MyBrushes.Red);
                    return;
                }

                Thread.Sleep(5000);

            }).ContinueWith(t =>
            {

                DLEDLightingHelper.Instance.PowerOff();

                this.Loading.Hide();

            });

        }

        #endregion

        #region RejudeResult
        private bool ResultRejude(string Result)
        {
            if (Result.Contains("fail"))
            {
                return false;
            }
            return true;
        }
        #endregion
        private void RefreshLightParameter()
        {
            this.ViewModel.TestInfo.SetMCValue =          TestConfig.Instance.SetMCValue;
            this.ViewModel.TestInfo.SetDCValue =          TestConfig.Instance.SetDCValue;
            this.ViewModel.TestInfo.SetBCValue =          TestConfig.Instance.SetBCValue;
            this.ViewModel.TestInfo.SetScaleValue = TestConfig.Instance.SetScaleValue;
            this.ViewModel.TestInfo.SetIledValue = TestConfig.Instance.SetIledValue;
            this.ViewModel.TestInfo.SetGCG1Value = TestConfig.Instance.SetGCG1Value;
            this.ViewModel.TestInfo.SetGCG2Value = TestConfig.Instance.SetGCG2Value;
            this.ViewModel.TestInfo.SetHLMSValue = TestConfig.Instance.SetHLMSValue;
            this.ViewModel.TestInfo.SetForLightValue =    TestConfig.Instance.SetForLightValue;
            this.ViewModel.TestInfo.SetBackLightValue =   TestConfig.Instance.SetBackLightValue;
            this.ViewModel.TestInfo.SetLocationICValue=   TestConfig.Instance.SetLocationICValue;
            this.ViewModel.TestInfo.SetLocationLedValue = TestConfig.Instance.SetLocationLedValue;
            this.ViewModel.TestInfo.SetLocationScanNumValue = TestConfig.Instance.SetLocationLedValue;

            this.ViewModel.TestInfo.ThreasholdValue = TestConfig.Instance.ThreasholdValue;
            this.ViewModel.TestInfo.MinAreaValue = TestConfig.Instance.MinAreaValue;
            this.ViewModel.TestInfo.MaxAreaValue = TestConfig.Instance.MaxAreaValue;
        }

        private bool SetMCDCBC(int MCValue, int DCValue, int BCValue)
        {
            bool isSuccess = true;

            AppendTestData("MC设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetMC(MCValue))
            {
                AppendTestData("MC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("MC设置成功", MyBrushes.Green);
            }

            AppendTestData("DC设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetDC(DCValue))
            {
                AppendTestData("DC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("DC设置成功", MyBrushes.Green);
            }

            AppendTestData("BC设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetBC(BCValue))
            {
                AppendTestData("BC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("BC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetGCG1GCG2HLMS(int GCG1Value, int GCG2Value, int HLMSValue)
        {
            bool isSuccess = true;

            AppendTestData("GCG1设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetGCG1(GCG1Value))
            {
                AppendTestData("GCG1设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("GCG1设置成功", MyBrushes.Green);
            }

            AppendTestData("GCG2设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetGCG2(GCG2Value))
            {
                AppendTestData("GCG2设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("GCG2设置成功", MyBrushes.Green);
            }

            AppendTestData("HLMS设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetHLMS(HLMSValue))
            {
                AppendTestData("HLMS设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("HLMS设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetMCBC(int MCValue, int BCValue)
        {
            bool isSuccess = true;

            AppendTestData("MC设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetMC(MCValue))
            {
                AppendTestData("MC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("MC设置成功", MyBrushes.Green);
            }

            AppendTestData("BC设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetBC(BCValue))
            {
                AppendTestData("BC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("BC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetMC(int MCValue)
        {
            bool isSuccess = true;

            AppendTestData("MC设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetMC(MCValue))
            {
                AppendTestData("MC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("MC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetDC(int DCValue)
        {
            bool isSuccess = true;

            AppendTestData("DC设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetDC(DCValue))
            {
                AppendTestData("DC设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("DC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetScale_Iled(int ScaleValue, int IledValue)
        {
            bool isSuccess = true;

            AppendTestData("Scale设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetSCALE(ScaleValue))
            {
                AppendTestData("Scale设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("Scale设置成功", MyBrushes.Green);
            }

            AppendTestData("ILED设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetILED(IledValue))
            {
                AppendTestData("ILED设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("ILED设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }

        private bool SetScale_SRC(int ScaleValue, int ISRCValue)
        {
            bool isSuccess = true;

            AppendTestData("Scale设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetSCALE(ScaleValue))
            {
                AppendTestData("Scale设置失败", MyBrushes.Red);

                isSuccess = false;
            }
            else
            {

                AppendTestData("Scale设置成功", MyBrushes.Green);
            }

            AppendTestData("SRC设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetSRC(ISRCValue))
            {
                AppendTestData("SRC设置失败", MyBrushes.Red);
                isSuccess = false;
            }
            else
            {

                AppendTestData("SRC设置成功", MyBrushes.Green);
            }

            return isSuccess;
        }
        private void RunPowerON()
        {
            if (!this.SetModel())
            {
                return;
            }

            //#region Pin短路开路测试
            //DLEDLightingHelper.Instance.GetPinOSTestData();
            //#endregion

            //#region 芯片待机电流
            //DLEDLightingHelper.Instance.GetLEDDriverICStandbyVolCurData();

            //#endregion

            //#region 芯片正常运行电流
            //DLEDLightingHelper.Instance.GetLEDDriverICWorkingVolCurData();

            //#endregion
            AppendTestData("PinOSTest", MyBrushes.TESTING);
            if (!ResultRejude(DLEDLightingHelper.Instance.GetPinOSTestData()))
            {
                AppendTestData("PinOSTest Fail", MyBrushes.Red);
                return;
            }
            AppendTestData("LEDDriverICStandbyVolCur", MyBrushes.TESTING);
            if (!ResultRejude(DLEDLightingHelper.Instance.GetLEDDriverICStandbyVolCurData()))
            {
                AppendTestData("LEDDriverICStandbyVolCur Fail", MyBrushes.Red);
                return;
            }
            AppendTestData("LEDDriverICWorkingVolCur", MyBrushes.TESTING);
            if (!ResultRejude(DLEDLightingHelper.Instance.GetLEDDriverICWorkingVolCurData()))
            {
                AppendTestData("LEDDriverICWorkingVolCur Fail", MyBrushes.Red);
                return;
            }
        }

        private void ALLLEDLight()
        {
            if (ViewModel.TestInfo.TestModelCode == 7 || ViewModel.TestInfo.TestModelCode == 16)
            {
                if (ViewModel.TestInfo.IsVLedSet)
                {
                    AppendTestData("VLED设置", MyBrushes.Yellow);

                    if (!DLEDLightingHelper.Instance.SetVBL(ViewModel.TestInfo.DvledValue))
                    {
                        AppendTestData("VLED设置失败", MyBrushes.Red);

                    }
                    else
                    {

                        AppendTestData("VLED设置成功", MyBrushes.Green);
                        Thread.Sleep(10);
                    }

                }
            }
            RunPowerON();

            int MC = ViewModel.TestInfo.SetMCValue;
            int DC = ViewModel.TestInfo.SetDCValue;
            int BC = ViewModel.TestInfo.SetBCValue;

            int Scale = ViewModel.TestInfo.SetScaleValue;
            int SRC = ViewModel.TestInfo.SetSRCValue;
            int Iled = ViewModel.TestInfo.SetIledValue;

            int GCG1 = ViewModel.TestInfo.SetGCG1Value;
            int GCG2 = ViewModel.TestInfo.SetGCG2Value;
            int HLMS = ViewModel.TestInfo.SetHLMSValue;

            int lightValue = ViewModel.TestInfo.SetForLightValue;

            if (ViewModel.TestInfo.TestModelCode == 1 || ViewModel.TestInfo.TestModelCode == 8 || ViewModel.TestInfo.TestModelCode == 9)
            {
                lightValue = 4095;
                SetMC(MC);
                AppendTestData(string.Format("全电流测试MC:{0}",MC), MyBrushes.TESTING);
            }else if (ViewModel.TestInfo.TestModelCode == 7 || ViewModel.TestInfo.TestModelCode == 16)
            {
               

                SetScale_SRC(Scale, SRC);
                AppendTestData(string.Format("全电流测试Scale:{0},SRC:{1}", Scale, SRC), MyBrushes.TESTING);
            }
            else if (ViewModel.TestInfo.TestModelCode == 10)
            {
                //lightValue = 65535;
                SetScale_Iled(Scale, Iled);
                AppendTestData(string.Format("全电流测试Scale:{0},ILED:{1}", Scale, Iled), MyBrushes.TESTING);
            }else if(ViewModel.TestInfo.TestModelCode == 13 || ViewModel.TestInfo.TestModelCode == 37)
            {
                SetGCG1GCG2HLMS(GCG1, GCG2, HLMS);
                AppendTestData(string.Format("全电流测试GCG1:{0}, GCG2:{1} , HLMS:{2}", GCG1, GCG2, HLMS), MyBrushes.TESTING);
            }
            else if (ViewModel.TestInfo.TestModelCode == 14 || ViewModel.TestInfo.TestModelCode == 15)
            {
                //lightValue = 4095;
                SetMCDCBC(MC, DC, BC);
                AppendTestData(string.Format("全电流测试MC:{0}, DC:{1} , BC:{2}", MC, DC, BC), MyBrushes.TESTING);
            }
            else
            {
                lightValue = 65535;
                SetMCDCBC(MC, DC, BC);
                AppendTestData(string.Format("全电流测试MC:{0}, DC:{1} , BC:{2}", MC,DC,BC), MyBrushes.TESTING);

            }

            
            DLEDLightingHelper.Instance.GetAllLEDTestData(lightValue);

        }

        int index = 0;
        private void SingleLEDLight()
        {
            int MC = ViewModel.TestInfo.SetMCValue;
            int DC = ViewModel.TestInfo.SetDCValue;
            int BC = ViewModel.TestInfo.SetBCValue;
            int Scale = ViewModel.TestInfo.SetScaleValue;
            int SRC = ViewModel.TestInfo.SetSRCValue;
            int Iled = ViewModel.TestInfo.SetIledValue;
            int GCG1 = ViewModel.TestInfo.SetGCG1Value;
            int GCG2 = ViewModel.TestInfo.SetGCG2Value;
            int HLMS = ViewModel.TestInfo.SetHLMSValue;

            int lightValue = ViewModel.TestInfo.SetForLightValue;
            int BackLightValue = ViewModel.TestInfo.SetBackLightValue;
            int LocationIC = ViewModel.TestInfo.SetLocationICValue;
            int LocationLed = ViewModel.TestInfo.SetLocationLedValue;
            int LocationScanNum = ViewModel.TestInfo.SetLocationScanNumValue;

            if (index == 0)
            {
                if (ViewModel.TestInfo.TestModelCode == 7 || ViewModel.TestInfo.TestModelCode == 16)
                {
                    if (ViewModel.TestInfo.IsVLedSet)
                    {
                        AppendTestData("VLED设置", MyBrushes.Yellow);

                        if (!DLEDLightingHelper.Instance.SetVBL(ViewModel.TestInfo.DvledValue))
                        {
                            AppendTestData("VLED设置失败", MyBrushes.Red);

                        }
                        else
                        {

                            AppendTestData("VLED设置成功", MyBrushes.Green);
                            Thread.Sleep(10);
                        }

                    }
                }
                RunPowerON();
                if (ViewModel.TestInfo.TestModelCode == 7 || ViewModel.TestInfo.TestModelCode == 16)
                {
                    SetScale_SRC(Scale, SRC);
                    AppendTestData(string.Format("全电流测试Scale:{0},SRC:{1}", Scale, SRC), MyBrushes.TESTING);
                }
                index = 1;
            }

           

            if (ViewModel.TestInfo.TestModelCode == 1 || ViewModel.TestInfo.TestModelCode == 8 || ViewModel.TestInfo.TestModelCode == 9 || ViewModel.TestInfo.TestModelCode == 7)
            {
                //lightValue = 4095;setDebugMode
                SetMC(MC);

                AppendTestData(string.Format("单LED点亮：LocationIC：{0}， LocationLED：{1}，MC:{2},LightValue:{3}",LocationIC,LocationLed, MC,lightValue), MyBrushes.Yellow);
            }
            else if (ViewModel.TestInfo.TestModelCode == 7 || ViewModel.TestInfo.TestModelCode == 16)
            {
                //if (index == 0)
                //{
                    //SetScale_SRC(Scale, SRC);
                    //AppendTestData(string.Format("全电流测试Scale:{0},SRC:{1}", Scale, SRC), MyBrushes.TESTING);
                //}
            }

            else if (ViewModel.TestInfo.TestModelCode == 10)
            {
                //lightValue = 65535;
                SetScale_Iled(Scale, Iled);
                AppendTestData(string.Format("单LED点亮：LocationIC：{0}， LocationLED：{1}，Scale:{2},ILED:{3},LightValue:{4}", LocationIC, LocationLed, Scale,Iled, lightValue), MyBrushes.Yellow);
            }
            else if (ViewModel.TestInfo.TestModelCode == 13 || ViewModel.TestInfo.TestModelCode == 37)
            {
                SetGCG1GCG2HLMS(GCG1, GCG2, HLMS);
                AppendTestData(string.Format("全电流测试GCG1:{0}, GCG2:{1} , HLMS:{2}", GCG1, GCG2, HLMS), MyBrushes.Yellow);
                AppendTestData(string.Format("单LED点亮：LocationScanNum :{0} LocationIC：{1}， LocationLED：{2}，GCG1:{3}, GCG2:{4} , HLMS:{5},LightValue:{6}", LocationScanNum, LocationIC, LocationLed, GCG1, GCG2, HLMS, lightValue), MyBrushes.Yellow);

                DLEDLightingHelper.Instance.ShowSingleScanLEDLocation(lightValue.ToString(),BackLightValue.ToString(),LocationIC.ToString(),LocationLed.ToString(),LocationScanNum.ToString());

                return;
            }else if (ViewModel.TestInfo.TestModelCode == 48)
            {
                SetDC(DC);
                AppendTestData(string.Format("单LED点亮：LocationIC：{0}， LocationLED：{1}， DC:{2} ,LightValue:{3}", LocationIC, LocationLed,  DC, lightValue), MyBrushes.Yellow);
            }
            else
            {
                //lightValue = 65535;
                SetMCDCBC(MC, DC, BC);
                AppendTestData(string.Format("单LED点亮：LocationIC：{0}， LocationLED：{1}，MC:{2},DC:{3},BC:{4},LightValue:{5}", LocationIC, LocationLed, MC,DC,BC, lightValue), MyBrushes.Yellow);

            }

            DLEDLightingHelper.Instance.ShowSingleLEDLocation(lightValue.ToString(),BackLightValue.ToString(),LocationIC.ToString(),LocationLed.ToString());

        }
        private void LoopSingleLEDLight()
        {
            RunPowerON();

            int MC = ViewModel.TestInfo.SetMCValue;
            int DC = ViewModel.TestInfo.SetDCValue;
            int BC = ViewModel.TestInfo.SetBCValue;

            int Scale = ViewModel.TestInfo.SetScaleValue;
            int Iled = ViewModel.TestInfo.SetIledValue;

            int lightValue = 0;

            if (ViewModel.TestInfo.TestModelCode == 1 || ViewModel.TestInfo.TestModelCode == 8 || ViewModel.TestInfo.TestModelCode == 9 || ViewModel.TestInfo.TestModelCode == 7)
            {
                lightValue = 4095;
                SetMC(MC);
            }
            else if (ViewModel.TestInfo.TestModelCode == 10)
            {
                lightValue = 65535;
                SetScale_Iled(Scale, Iled);
            }
            else
            {
                lightValue = 65535;
                SetMCDCBC(MC, DC, BC);

            }

            DLEDLightingHelper.Instance.GetSingleLEDTestData(lightValue);

        }

        private void LoopICLight()
        {
            RunPowerON();

            int MC = ViewModel.TestInfo.SetMCValue;
            int DC = ViewModel.TestInfo.SetDCValue;
            int BC = ViewModel.TestInfo.SetBCValue;

            int Scale = ViewModel.TestInfo.SetScaleValue;
            int Iled = ViewModel.TestInfo.SetIledValue;

            int GCG1 = ViewModel.TestInfo.SetGCG1Value;
            int GCG2 = ViewModel.TestInfo.SetGCG2Value;
            int HLMS = ViewModel.TestInfo.SetHLMSValue;

            int lightValue = 0;

            if (ViewModel.TestInfo.TestModelCode == 1 || ViewModel.TestInfo.TestModelCode == 8 || ViewModel.TestInfo.TestModelCode == 9 || ViewModel.TestInfo.TestModelCode == 7)
            {
                lightValue = 4095;
                SetMC(MC);
            }
            else if (ViewModel.TestInfo.TestModelCode == 10)
            {
                lightValue = 65535;
                SetScale_Iled(Scale, Iled);
            }
            else if (ViewModel.TestInfo.TestModelCode == 13)
            {
                lightValue = 4095;
                SetGCG1GCG2HLMS(GCG1, GCG2, HLMS);
                
            }
            else
            {
                lightValue = 65535;
                SetMCDCBC(MC, DC, BC);

            }

            DLEDLightingHelper.Instance.GetICLEDTestData(lightValue);

        }

        #endregion

        #region 图像处理
        private void ThresholdImage()
        {
            int threasholdValue;

            if (!int.TryParse(this.txtThresholdValueName.Text, out threasholdValue))
            {

                this.ShowDialog("文本要为整型数字", "提示", MessageBoxButton.OK, DialogIcon.Error);
                return;

            }

            string ImagePath = txtImagePathName.Text;

            if (!File.Exists(ImagePath))
            {
                this.ShowDialog("ImageFile路径不存在", "提示", MessageBoxButton.OK, DialogIcon.Error);
                return;
            }

            Mat srcImage = Cv2.ImRead(ImagePath, ImreadModes.AnyColor);

            Mat thresholdImage = new Mat();

            Cv2.Blur(srcImage, srcImage, new OpenCvSharp.Size(3, 3));

            Cv2.Threshold(srcImage, thresholdImage, threasholdValue, 255, ThresholdTypes.Binary);

            BitmapImage bitmapImage = MatToBitmapImage(thresholdImage);

            imgCCD1.Source = bitmapImage;

        }

        private void FindContoursArea()
        {
            string ImagePath = txtImagePathName.Text;

            if (!File.Exists(ImagePath))
            {
                this.ShowDialog("ImageFile路径不存在", "提示", MessageBoxButton.OK, DialogIcon.Error);
                return;
            }

            Mat srcImage = Cv2.ImRead(ImagePath, ImreadModes.AnyColor);

            OpenCvSharp.Point point = GetPositionImage(ImagePath);

            OpenCvSharp.Point centerPoint = new OpenCvSharp.Point(point.X + TestConfig.Instance.StartPointX,point.Y+TestConfig.Instance.StartPointY);

            AppendTestData(string.Format("Center Point[{0},{1}]", centerPoint.X, centerPoint.Y), MyBrushes.RichGreen);

            Mat dstImage = beanGoOpenCVHelper.DrawCircle(srcImage,centerPoint, 20);

            imgCCD1.Source = MatToBitmapImage(dstImage);
        }

        //private void CreateXlse()
        //{
        //    //创建一个excel
        //    IWorkbook workbook = new HSSFWorkbook();
        //    //创建一张sheet
        //    ISheet sheet = workbook.CreateSheet("sheet1");
        //    //使用文件流写入数据
        //    using (FileStream fileStream = new FileStream("C:\\Users\\beango.cheng\\Desktop\\test1.xls", FileMode.OpenOrCreate, FileAccess.Write))
        //    {
        //        int index = 0;

        //        for (int iRow = 0; iRow < TestConfig.Instance.SingleRowsCount; iRow++)
        //        {

        //            IRow row = sheet.CreateRow(iRow);

        //            for (int col = 0; col < TestConfig.Instance.SingleColsCount; col++)
        //            {
        //                index = iRow * TestConfig.Instance.SingleColsCount + col;

        //                ICell cell = row.CreateCell(col);

        //                if (cell != null)
        //                {

        //                    string value = TestConfig.Instance.SingleROIRectList.ToArray()[TestConfig.Instance.SingleROIRectList.Count() - index - 1].LED;
        //                    Console.WriteLine(value);
        //                    cell.SetCellValue(value);
        //                }
        //            }
        //        }


        //        workbook.Write(fileStream);
        //    }
        //}

        private void DoImage()
        {
            string ImagePath = "C:\\Users\\beango.cheng\\Desktop\\1_12.bmp";

            if (!File.Exists(ImagePath))
            {
                //if (!this.CCD.SaveImage(ImagePath))
                //{
                this.ShowDialog("不存在文件或保存失败！", "预览失败", MessageBoxButton.OK, DialogIcon.Cry);
                return;
                //}
            }

            Mat srcImage = Cv2.ImRead(ImagePath, ImreadModes.AnyColor);
            //Mat RoIImage =

            //Cv2.CvtColor(srcImage, srcImage, ColorConversionCodes.GRAY2BGR);

            //srcImage = this.RotateAngleImage(srcImage, TestConfig.Instance.AngleValue);

            foreach (MyROIRect roiRect in TestConfig.Instance.ROIRectList)
            {

                if (roiRect.IsEnable)
                {
                    OpenCvSharp.Rect roi = new OpenCvSharp.Rect(roiRect.X, roiRect.Y, roiRect.Width, roiRect.Height);//首先要用个rect确定我们的兴趣区域在哪


                    Mat ROIImage = new Mat(srcImage, roi);
                    Cv2.ImShow("RoiImage", ROIImage);

                    List<OpenCvSharp.Point[]> points = beanGoOpenCVHelper.MyFindContoursArea(ROIImage, 10, 5000, 100);

                    OpenCvSharp.Rect2f rect2F = beanGoOpenCVHelper.MyGetMinAreaRectangleRect2f(points);


                    OpenCvSharp.Rect PositionRectangle = new OpenCvSharp.Rect((int)rect2F.X, (int)rect2F.Y, (int)rect2F.Width, (int)rect2F.Height);

                    OpenCvSharp.Rect LightroiRect = new OpenCvSharp.Rect((int)rect2F.X + roi.X - (int)(rect2F.Width / 2), (int)rect2F.Y + roi.Y - (int)(rect2F.Height / 2), (int)rect2F.Width, (int)rect2F.Height);

                    Cv2.Rectangle(srcImage, LightroiRect, OpenCvSharp.Scalar.Red, 2);

                    Cv2.ImShow("RoiImage", srcImage);
                }

            }

            imgCCD1.Source = MatToBitmapImage(srcImage);
        }

        private OpenCvSharp.Point GetPositionImage(string ImagePath)
        {
            //string ImagePath = "C:\\Users\\beango.cheng\\Desktop\\1_12.bmp";

            // OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);  //

            Mat srcImage = Cv2.ImRead(ImagePath, ImreadModes.AnyColor);
            //Mat RoIImage =

            //Cv2.CvtColor(srcImage, srcImage, ColorConversionCodes.GRAY2BGR);

            //srcImage = this.RotateAngleImage(srcImage, TestConfig.Instance.AngleValue);

            OpenCvSharp.Point point = new OpenCvSharp.Point();

            foreach (MyROIRect roiRect in TestConfig.Instance.ROIRectList)
            {

                if (roiRect.IsEnable)
                {
                    OpenCvSharp.Rect roi = new OpenCvSharp.Rect(roiRect.X, roiRect.Y, roiRect.Width, roiRect.Height);//首先要用个rect确定我们的兴趣区域在哪

                    Console.WriteLine("111");

                    Mat ROIImage = new Mat(srcImage, roi);

                    Console.WriteLine("222");

                    List<OpenCvSharp.Point[]> points = beanGoOpenCVHelper.MyFindContoursArea(ROIImage, ViewModel.TestInfo.MinAreaValue, ViewModel.TestInfo.MaxAreaValue, ViewModel.TestInfo.ThreasholdValue);

                    Console.WriteLine("333------------:" + points.Count());

                    if (points.Count() == 0)
                    {
                        return point;
                    }

                    Console.WriteLine("444");

                    OpenCvSharp.Rect2f rect2F = beanGoOpenCVHelper.MyGetMinAreaRectangleRect2f(points);

                    point = new OpenCvSharp.Point(rect2F.X, rect2F.Y);

                    Console.WriteLine("555");

                }

            }

            return point;

        }

        public BitmapImage MatToBitmapImage(Mat image)
        {

            System.Drawing.Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image);

            using (var ms = new MemoryStream())

            {

                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                BitmapImage result = new BitmapImage();

                result.BeginInit();

                result.CacheOption = BitmapCacheOption.OnLoad;

                result.StreamSource = ms;

                result.EndInit();

                return result;

            }

        }

        #endregion

        #region 当设备连接或断开后更新开始测试按钮的状态
        private void UpdateStartButtonState()
        {
            ViewModel.TestInfo.EnabledStartButton = true; //RelayBoardHelper.RelayBoards.All(s => s.IsConnect) && this._Meter.IsConnected;

            if (ViewModel.TestInfo.EnabledStartButton)
            {
                ViewModel.Status.Update("Ready", MyBrushes.RichBlue);
            }
            else
            {
                ViewModel.Status.Update("Wating...", MyBrushes.RichRed);
            }
        }
        #endregion

        #region Camera

        System.Windows.Forms.PictureBox m_pictureBox;

        private Bitmap tempBitmap;
        private void Camera_CameraImageEvent(Bitmap bmp)
        {
            //使用委托进行跨线程交互 防止线程卡死状态在Invoke前面加一个Begin
            m_pictureBox.BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate
            {
                Bitmap old = m_pictureBox.Image as Bitmap;
                m_pictureBox.Image = bmp;
                tempBitmap = bmp;
                if (old != null)
                    old.Dispose();
            }));

            //this.Dispatcher.BeginInvoke((Action)delegate
            //{
            //    try  
            //    {

            //        this.imgCCD.Source = bitmapToimage(bmp);//BitmapFrame.Create(this.ImageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

            //        tempBitmap = bmp;

            //        if (bmp != null)
            //        {
            //            bmp.Dispose();
            //        }

            //    }
            //    catch (Exception)
            //    {
            //        camera.Stop();
            //        this.camera.DestroyCamera();
            //    }

            //});
        }

        public BitmapImage bitmapToimage(Bitmap bitimg)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                bitimg.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                stream.Position = 0;
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.StreamSource = stream;
                result.EndInit();
                result.Freeze();
                return result;
            }
        }

        /// <summary>
        /// 保存图片并返回文件名
        /// </summary>
        /// <returns></returns>
        public bool SaveImage(string FileName)
        {
            try
            {
                if (this.tempBitmap == null)
                {
                    return false;
                }

                Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(this.tempBitmap);

                Mat grayImage = new Mat();

                Cv2.CvtColor(mat, grayImage, ColorConversionCodes.BGR2GRAY);

                grayImage.SaveImage(FileName);

                //Bitmap newbitmap = tempBitmap.Clone(new System.Drawing.Rectangle(0, 0, tempBitmap.Width, tempBitmap.Height), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                //Bitmap saveBitmap = ToGrayscale(bitmap1);
                //bitmap1.RotateFlip(RotateFlipType.Rotate180FlipNone);
                //bitmap1 = tempBitmap.Clone(new System.Drawing.Rectangle(0, 0, tempBitmap.Width, tempBitmap.Height), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                //newbitmap.Save(FileName, System.Drawing.Imaging.ImageFormat.Bmp);

                return true;
            }
            catch (Exception ex)
            {
                Bandit.Helpers.LogHelper.Error(ex, "UcCCD.SaveImage");
                return false;
            }

        }

        #endregion

        #region Serial
        private void InitMiniLedLightUpSerialPort()
        {

            //DLEDLightingHelper.Instance.Reset();

            Thread.Sleep(100);

            DLEDLightingHelper.Instance.OnConnectedChanged += Instance_OnConnectedChanged;

            DLEDLightingHelper.Instance.OnError += (sender, e) =>
            {
                LogHelper.Error(e.Exception, e.Title);
            };

            DLEDLightingHelper.Instance.Connect("\r\n", 1000000, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One);

        }

        private void Instance_OnConnectedChanged(DeviceBase sender, bool isConnect)
        {
            if (isConnect)
            {

                ViewModel.UsbStatus.Update(string.Format("Serial Connected"), MyBrushes.Green);


            }
            else
            {
                ViewModel.UsbStatus.Update("Serial DisConnect", MyBrushes.Red);
            }
        }

        #endregion

        #region ChangePage
        private Grid CurrentShowGrid { get; set; }

        private void ChangePage(Grid grid)
        {
            if (grid == this.CurrentShowGrid)
            {
                return;
            }
            else
            {
                if (grid == this.GridEnginer)
                {
                    ViewModel.EngineerMode = true;
                }
                if (grid == this.GridOperator)
                {
                    //Core.TestConfig.SaveConfig();
                    ViewModel.EngineerMode = false;
                }

                this.CurrentShowGrid.Hide(Bandit.UI.Animation.Scale | Bandit.UI.Animation.Opacity, 0.5, delegate
                {
                    this.CurrentShowGrid = grid;

                    grid.Show(Bandit.UI.Animation.Scale | Bandit.UI.Animation.Opacity, 0.5);
                });
            }

        }
        #endregion

        #region [开始测试]

        #region dd
        //private void StartTest1()
        //{
        //    if (!ViewModel.TestInfo.EnabledStartButton)
        //    {
        //        return;
        //    }

        //    this.rtxtTestData.Document.Blocks.Clear();
        //    //测试开始，更新界面显示
        //    ViewModel.TestInfo.TestStart();

        //    //更新状态栏显示
        //    ViewModel.Status.Update("Testing...", MyBrushes.RichYellow);

        //    //显示测试中效果UI
        //    this.Loading.Show("Testing...");

        //    Task.Factory.StartNew(() =>
        //    {
        //        //在这里执行测试功能
        //        #region Model 设置
        //        AppendTestData("Model设置", MyBrushes.Yellow);
        //        if (!DLEDLightingHelper.Instance.SetCaseCode(ViewModel.TestInfo.TestModelCode))
        //        {

        //            return;
        //        }
        //        else
        //        {
        //            AppendTestData("Model设置成功", MyBrushes.Green);
        //        }


        //        if (ViewModel.TestInfo.IsVLedSet)
        //        {
        //            AppendTestData("VLED设置", MyBrushes.Yellow);

        //            if (!DLEDLightingHelper.Instance.SetVBL(ViewModel.TestInfo.DvledValue))
        //            {
        //                AppendTestData("VLED设置失败", MyBrushes.Red);

        //                return;
        //            }
        //            else
        //            {

        //                AppendTestData("VLED设置成功", MyBrushes.Green);
        //            }

        //        }

        //        if (ViewModel.TestInfo.IsOCPOVPSet)
        //        {
        //            AppendTestData("过压过流设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetOCPOVP(ViewModel.TestInfo.DvLedOvpValue, ViewModel.TestInfo.DvLedOcpValue, ViewModel.TestInfo.DICOvpValue, ViewModel.TestInfo.DICOcpValue * 1000))
        //            {
        //                AppendTestData("过压过流设置失败", MyBrushes.Red);

        //                return;
        //            }
        //            else
        //            {

        //                AppendTestData("过压过流设置成功", MyBrushes.Green);
        //            }
        //        }

        //        if (ViewModel.TestInfo.IsMCSet)
        //        {
        //            AppendTestData("MC设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetMC(ViewModel.TestInfo.IMCValue))
        //            {
        //                AppendTestData("MC设置失败", MyBrushes.Red);
        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("MC设置成功", MyBrushes.Green);
        //            }
        //        }

        //        if (ViewModel.TestInfo.IsDCSet)
        //        {
        //            AppendTestData("DC设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetDC(ViewModel.TestInfo.IDCValue))
        //            {
        //                AppendTestData("DC设置失败", MyBrushes.Red);

        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("DC设置成功", MyBrushes.Green);
        //            }

        //        }

        //        if (ViewModel.TestInfo.IsBCSet)
        //        {
        //            AppendTestData("BC设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetBC(ViewModel.TestInfo.IBCValue))
        //            {
        //                AppendTestData("BC设置失败", MyBrushes.Red);
        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("BC设置成功", MyBrushes.Green);
        //            }
        //        }

        //        if (ViewModel.TestInfo.IsScaleSet)
        //        {
        //            AppendTestData("Scale设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetSCALE(ViewModel.TestInfo.IScaleValue))
        //            {
        //                AppendTestData("Scale设置失败", MyBrushes.Red);
        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("Scale设置成功", MyBrushes.Green);
        //            }
        //        }

        //        if (ViewModel.TestInfo.IsILEDSet)
        //        {
        //            AppendTestData("ILED设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetILED(ViewModel.TestInfo.IILEDValue))
        //            {
        //                AppendTestData("ILED设置失败", MyBrushes.Red);

        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("ILED设置成功", MyBrushes.Green);
        //            }
        //        }

        //        if (ViewModel.TestInfo.IsSRCSet)
        //        {
        //            AppendTestData("SRC设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetSRC(ViewModel.TestInfo.ISrcValue))
        //            {
        //                AppendTestData("SRC设置失败", MyBrushes.Red);
        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("SRC设置成功", MyBrushes.Green);
        //            }
        //        }

        //        if (ViewModel.TestInfo.IsLEDNUMSet)
        //        {
        //            AppendTestData("LEDNUM设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetLEDNUM(ViewModel.TestInfo.ILEDNUMValue))
        //            {
        //                AppendTestData("LEDNUM设置失败", MyBrushes.Red);
        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("LEDNUM设置成功", MyBrushes.Green);
        //            }
        //        }


        //        if (ViewModel.TestInfo.IsRSETSet)
        //        {
        //            AppendTestData("RSET设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetRSET(ViewModel.TestInfo.IRSETValue))
        //            {
        //                AppendTestData("RSET设置失败", MyBrushes.Red);
        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("RSET设置成功", MyBrushes.Green);
        //            }
        //        }


        //        if (ViewModel.TestInfo.IsCLKSet)
        //        {
        //            AppendTestData("CLK设置", MyBrushes.Yellow);
        //            if (!DLEDLightingHelper.Instance.SetCLK(ViewModel.TestInfo.ICLKValue))
        //            {
        //                AppendTestData("CLK设置失败", MyBrushes.Red);
        //                return;
        //            }
        //            else
        //            {
        //                AppendTestData("CLK设置成功", MyBrushes.Green);
        //            }
        //        }

        //        #endregion

        //        DLEDLightingHelper.Instance.GetPinOSTestData();

        //        DLEDLightingHelper.Instance.GetLEDDriverICStandbyVolCurData();

        //        DLEDLightingHelper.Instance.GetLEDDriverICWorkingVolCurData();

        //        //DLEDLightingHelper.Instance.GetAllLEDTestData(1000);

        //        Thread.Sleep(1000);


        //        int MC = ViewModel.TestInfo.SetMCValue;
        //        int DC = ViewModel.TestInfo.SetDCValue;
        //        int BC = ViewModel.TestInfo.SetBCValue;
        //        int Scale = ViewModel.TestInfo.SetScaleValue;
        //        int Iled = ViewModel.TestInfo.SetIledValue;

        //        int lightValue = ViewModel.TestInfo.SetForLightValue;
        //        int BackLightValue = ViewModel.TestInfo.SetBackLightValue;
        //        int LocationIC = ViewModel.TestInfo.SetLocationICValue;
        //        int LocationLed = ViewModel.TestInfo.SetLocationLedValue;

        //        if (ViewModel.TestInfo.TestModelCode == 1 || ViewModel.TestInfo.TestModelCode == 8 || ViewModel.TestInfo.TestModelCode == 9 || ViewModel.TestInfo.TestModelCode == 7)
        //        {
        //            lightValue = 4095;
        //            SetMC(MC);
        //        }
        //        else if (ViewModel.TestInfo.TestModelCode == 10)
        //        {
        //            //lightValue = 65535;
        //            SetScale_Iled(Scale, Iled);
        //        }
        //        else
        //        {
        //            lightValue = 65535;
        //            SetMCDCBC(MC, DC, BC);

        //        }

        //        // DLEDLightingHelper.Instance.ShowSingleLEDLocation(lightValue.ToString(), BackLightValue.ToString(), LocationIC.ToString(), LocationLed.ToString());

        //        for (int ic = 0; ic < TestConfig.Instance.ICCount; ic++)
        //        {

        //            for (int iLed = 0; iLed < TestConfig.Instance.LedCount; iLed++)
        //            {
        //                DLEDLightingHelper.Instance.ShowSingleLEDLocation(lightValue.ToString(), "10", ic.ToString(), iLed.ToString());

        //                Thread.Sleep(800);

        //                if (tempBitmap != null)
        //                {
        //                    Bitmap bitmap = tempBitmap;//camera.GetOneBitmapImage();

        //                    //创建线程对象

        //                    string saveDir = string.Format(@"{0}bmpPath\", this.GetBaseDirectory());

        //                    if (!System.IO.Directory.Exists(saveDir))
        //                    {
        //                        System.IO.Directory.CreateDirectory(saveDir);
        //                    }

        //                    string imageFileName = saveDir + string.Format(@"{0}_IC{1}_LED{2}_{3}.bmp", ViewModel.TestInfo.Barcode, ic, iLed, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));


        //                    this.Dispatcher.BeginInvoke((Action)delegate
        //                    {
        //                        try
        //                        {
        //                            for (int i = 0; i < 100; i++)
        //                            {
        //                                if (SaveImage(imageFileName))
        //                                {
        //                                    Thread.Sleep(200);
        //                                    if (File.Exists(imageFileName))
        //                                    {
        //                                        this.imgCCD1.Source = bitmapToimage(bitmap);//BitmapFrame.Create(this.ImageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

        //                                        Console.WriteLine("图片保存成功 ---:" + i);

        //                                        break;

        //                                    }
        //                                    else
        //                                    {
        //                                        Console.WriteLine("图片不存在，重新保存---:" + i);
        //                                        Thread.Sleep(300);
        //                                    }
        //                                }

        //                                Console.WriteLine("图片保存失败，重新保存---:" + i);
        //                            }
        //                        }
        //                        catch (Exception)
        //                        {

        //                        }

        //                    });

        //                    while (true)
        //                    {
        //                        if (File.Exists(imageFileName))
        //                        {
        //                            try
        //                            {
        //                                Thread.Sleep(100);

        //                                OpenCvSharp.Point point = GetPositionImage(imageFileName);

        //                                if (point.X == 0 && point.Y == 0)
        //                                {
        //                                    break;
        //                                }


        //                                MyROIRect myROIRect = TestConfig.Instance.SingleROIRectList.First(s => s.X <= point.X && (s.X + s.Width) >= point.X && s.Y <= point.Y && (s.Y + s.Height) >= point.Y);

        //                                if (myROIRect != null)
        //                                {
        //                                    myROIRect.LED = string.Format("{0}_{1}", ic, iLed + 1);
        //                                }

        //                                break;

        //                            }
        //                            catch (Exception ex)
        //                            {
        //                                Console.WriteLine("Opencv Error:" + ex.Message);
        //                                break;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            Console.WriteLine("图片不存在");
        //                            Thread.Sleep(10);
        //                        }
        //                    }
        //                }

        //                Thread.Sleep(100);
        //            }

        //        }


        //        CreateXlse();

        //        Thread.Sleep(1000);


        //    }).ContinueWith(task =>
        //    {
        //        this.Loading.Hide();

        //        FinishTest(false);
        //    });
        //}
        #endregion

        List<LEDPoint> LEDPoints = new List<LEDPoint>();


        /// <summary>
        /// 1、在app.config中添加新增的专案信息
        /// 2、配置 专案 、设置IC个数、 设置每个IC的LED个数【LED个数】
        /// 3、点亮、配置一个适当的亮度、全亮取图保存。小画家打开截取 模板匹配图，命名temp.png存工程路径下。
        /// 4、进配置，选择全亮图片，配置有效区域 1个大区域--> 选 行区域  每行把灯尽量在有效区域内。
        /// 5、点开始
        /// 6、编辑xls文件。检查是否正确。
        /// </summary>
        private void StartTest()
        {
            
            this.rtxtTestData.Document.Blocks.Clear();
            //测试开始，更新界面显示
            ViewModel.TestInfo.TestStart();

            //更新状态栏显示
            ViewModel.Status.Update("Testing...", MyBrushes.RichYellow);

            //显示测试中效果UI
            this.Loading.Show("Testing...");

            Task.Factory.StartNew(() =>
            {
                //在这里执行测试功能
                if (!SetModel())
                {
                    return;
                }

                DLEDLightingHelper.Instance.GetPinOSTestData();

                DLEDLightingHelper.Instance.GetLEDDriverICStandbyVolCurData();

                DLEDLightingHelper.Instance.GetLEDDriverICWorkingVolCurData();

                //DLEDLightingHelper.Instance.GetAllLEDTestData(1000);

                Thread.Sleep(1000);


                int MC = ViewModel.TestInfo.SetMCValue;
                int DC = ViewModel.TestInfo.SetDCValue;
                int BC = ViewModel.TestInfo.SetBCValue;

                int Scale = ViewModel.TestInfo.SetScaleValue;
                int SRC = ViewModel.TestInfo.SetSRCValue; 
                int Iled = ViewModel.TestInfo.SetIledValue;

                int lightValue = ViewModel.TestInfo.SetForLightValue;
                int BackLightValue = ViewModel.TestInfo.SetBackLightValue;
                int LocationIC = ViewModel.TestInfo.SetLocationICValue;
                int LocationLed = ViewModel.TestInfo.SetLocationLedValue;

                if (ViewModel.TestInfo.TestModelCode == 1 || ViewModel.TestInfo.TestModelCode == 8 || ViewModel.TestInfo.TestModelCode == 9 )
                {
                    lightValue = 4095;
                    SetMC(MC);
                }
                else if( ViewModel.TestInfo.TestModelCode == 7 || ViewModel.TestInfo.TestModelCode == 16)
                {
                    SetScale_SRC(Scale, SRC);
                }
                else if (ViewModel.TestInfo.TestModelCode == 10)
                {
                    //lightValue = 65535;
                    SetScale_Iled(Scale, Iled);
                }else if(ViewModel.TestInfo.TestModelCode == 13)
                {
                    this.ShowDialog("Case 13 无此功能，待开发", "结束测试");
                    return;
                }else if(ViewModel.TestInfo.TestModelCode == 14 || ViewModel.TestInfo.TestModelCode == 15)
                {
                    lightValue = 4095;
                    SetMCDCBC(MC, DC, BC);
                } else if(ViewModel.TestInfo.TestModelCode == 48)
                {
                    lightValue = 65535;
                    SetDC( DC );
                }
                else
                {
                    lightValue = 65535;
                    SetMCDCBC(MC, DC, BC);
                }
                //ViewModel.mySingleROIRectList.Clear();
                ViewModel.mySingleROIRectList = new Bandit.BanditCollection<MyROIRect>();

                foreach (var v in TestConfig.Instance.SingleROIRectList)
                {
                    v.LEDPoints.Clear();
                    v.LEDPoints = new List<LEDPoint>();

                    ViewModel.mySingleROIRectList.Add(v);

                }
                //TestConfig.Instance.SingleROIRectList.Select(x => x.LEDPoints = new List<LEDPoint>());
                // DLEDLightingHelper.Instance.ShowSingleLEDLocation(lightValue.ToString(), BackLightValue.ToString(), LocationIC.ToString(), LocationLed.ToString());

                LEDPoints = new List<LEDPoint>();
                int inum = 0;
                //TestConfig.Instance.ICCount
                for (int ic = 0; ic < TestConfig.Instance.ICCount; ic++)
                {
                    int width1 = 3088;
                    int height1 = 2064;

                    string saveDir1 = string.Format(@"{0}ICPointImages\", this.GetBaseDirectory());
                    if (!System.IO.Directory.Exists(saveDir1))
                    {
                        System.IO.Directory.CreateDirectory(saveDir1);
                    }
                    string path1 = string.Format("{0}{1}_Image_{2}.bmp", saveDir1,ic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss"));

                    Mat image1 = new Mat(height1, width1, MatType.CV_8UC3, Scalar.All(0));
                    //TestConfig.Instance.LedCount
                    for (int iLed = 0; iLed < TestConfig.Instance.LedCount; iLed++)
                    {
                        DLEDLightingHelper.Instance.ShowSingleLEDLocation(lightValue.ToString(), "10", ic.ToString(), iLed.ToString());
                        AppendTestData(string.Format("点灯 IC：{0}--Led：{1}", ic, iLed + 1),MyBrushes.Yellow);
                        Thread.Sleep(1000);

                        if (tempBitmap != null)
                        {
                            Bitmap bitmap = tempBitmap;//camera.GetOneBitmapImage();

                            //创建线程对象

                            string saveDir = string.Format(@"{0}bmpPath\", this.GetBaseDirectory());

                            if (!System.IO.Directory.Exists(saveDir))
                            {
                                System.IO.Directory.CreateDirectory(saveDir);
                            }

                            string imageFileName = saveDir + string.Format(@"{0}_IC{1}_LED{2}_{3}.bmp", ViewModel.TestInfo.Barcode, ic, iLed, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));

                            Thread.Sleep(100);

                            try
                            {
                                this.Dispatcher.BeginInvoke((Action)delegate
                                {
                                    for (int i = 0; i < 100; i++)
                                    {
                                        if (SaveImage(imageFileName))
                                        {
                                            Thread.Sleep(200);
                                            if (File.Exists(imageFileName))
                                            {

                                       
                                            //this.imgCCD1.Source = bitmapToimage(bitmap);//BitmapFrame.Create(this.ImageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

                                       

                                            Console.WriteLine("图片保存成功 ---:" + i);

                                                break;

                                            }
                                            else
                                            {
                                                Console.WriteLine("图片不存在，重新保存---:" + i);
                                                Thread.Sleep(300);
                                            }
                                        }

                                        Console.WriteLine("图片保存失败，重新保存---:" + i);
                                    }
                                });
                            }
                            catch (Exception)
                            {

                            }
                  
                            while (true)
                            {
                                if (File.Exists(imageFileName))
                                {
                                    try
                                    {
                                        Thread.Sleep(100);

                                        string tempPath = string.Format("{0}temp.PNG", this.GetBaseDirectory());
                                        OpenCvSharp.Point point = beanGoOpenCVHelper.MatchTemplateImage(imageFileName, tempPath);//GetPositionImage(imageFileName);

                                       
                                        if (point.X == 0 && point.Y == 0)
                                        {
                                            AppendTestData(string.Format("{0}-{1}匹配点：【{2}，{3}】", ic, iLed + 1,point.X,point.Y), MyBrushes.Red);
                                            break;
                                        }

                                        AppendTestData(string.Format("{0}-{1}匹配点：【{2}，{3}】", ic, iLed + 1, point.X, point.Y), MyBrushes.Green);
                                        LEDPoint lEDPoint = new LEDPoint();
                                        lEDPoint.Num = ++inum;
                                        lEDPoint.x = point.X;
                                        lEDPoint.y = point.Y;
                                        lEDPoint.Led = string.Format("{0}_{1}", ic, iLed + 1);

                                        LEDPoints.Add(lEDPoint);


                                        int x = TestConfig.Instance.ROIRectList[0].X;
                                        int y = TestConfig.Instance.ROIRectList[0].Y;

                                        point.X = point.X + 30; point.Y = point.Y + 30;

                                        MyROIRect myROIRect = ViewModel.mySingleROIRectList.First(s => (s.X+x) <= point.X && (s.X + x + s.Width) >= point.X && (s.Y + y) <= point.Y && (s.Y + y + s.Height) >= point.Y);

                                        if (myROIRect != null)
                                        {
                                            AppendTestData(string.Format("{0}---- add Led: {1},个数:{2}",myROIRect.Name, lEDPoint.Led,myROIRect.LEDPoints.Count()), MyBrushes.Blue);
                                            myROIRect.LEDPoints.Add(lEDPoint);
                                        }

                                        Cv2.Circle(image1, new OpenCvSharp.Point(lEDPoint.x, lEDPoint.y), 3, Scalar.White, -1); // 绘制点

                                        Cv2.PutText(image1, lEDPoint.Led, new OpenCvSharp.Point(lEDPoint.x, lEDPoint.y), HersheyFonts.HersheySimplex, 0.4, Scalar.Green, 1);
                                    
                                    break;

                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("Opencv Error:" + ex.Message);
                                        break;
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("图片不存在");
                                    Thread.Sleep(10);
                                }
                            }
                        }

                        Thread.Sleep(100);
                    }

                    image1.ImWrite(path1);
                }

                int width = 3088;
                int height = 2064;
                Mat image = new Mat(height, width, MatType.CV_8UC3, Scalar.All(0));

                // 绘制多个点
                foreach (var p in LEDPoints)
                {
                    Cv2.Circle(image, new OpenCvSharp.Point(p.x,p.y), 3, Scalar.White, -1); // 绘制点

                    Cv2.PutText(image, p.Led, new OpenCvSharp.Point(p.x, p.y), HersheyFonts.HersheySimplex, 0.4, Scalar.Green, 1);
                }
                string saveDir2 = string.Format(@"{0}ICPointImages\", this.GetBaseDirectory());

                if (!System.IO.Directory.Exists(saveDir2))
                {
                    System.IO.Directory.CreateDirectory(saveDir2);
                }
                //string path = string.Format("C:\\Users\\beango.cheng\\Desktop\\heImage_{0}.bmp", DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss"));
                string path = string.Format("{0}heImage_{1}.bmp", saveDir2, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss"));

                image.ImWrite(path);

                foreach (var i in LEDPoints)
                {
                    AppendTestData(i.Num + "," + i.Led + "," + new OpenCvSharp.Point(i.x, i.y),MyBrushes.PASS);
                }

                CreateXlse1();

                while (true)
                {
                    if (File.Exists(path))
                    {
                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            this.imgCCD1.Source = new BitmapImage(new Uri(path, UriKind.Absolute));//打开图片//bitmapToimage(bitmap);//BitmapFrame.Create(this.ImageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        }));

                        break;
                    }

                }
                
                Thread.Sleep(1000);


            }).ContinueWith(task =>
            {
                this.Loading.Hide();

                DLEDLightingHelper.Instance.PowerOff();

                FinishTest(false);
            });
        }

        private void CreateXlse1()
        {
           
            foreach(var v in ViewModel.mySingleROIRectList)
            {
                foreach(var v2 in v.LEDPoints)
                {
                    AppendTestData(string.Format("x:{0}_y:{1}={2}_{3}", v2.x, v2.y,v2.Num, v2.Led),MyBrushes.Red);
                }

                v.LEDPoints = v.LEDPoints.OrderBy(s => s.x).ToList();

                foreach (var v2 in v.LEDPoints)
                {
                    AppendTestData(string.Format("x:{0}_y:{1}={2}_{3}", v2.x, v2.y, v2.Num, v2.Led), MyBrushes.Green);
                }

                //List<MyROIRect> list = new List<MyROIRect>();
                //foreach(var a in v.LEDPoints)
                //{
                //    if(list.Contains(a))

                //}

            }
            //创建一个excel
            IWorkbook workbook = new HSSFWorkbook();
            //创建一张sheet
            ISheet sheet = workbook.CreateSheet("sheet1");
            string saveDir2 = string.Format(@"{0}ICPointImages\", this.GetBaseDirectory());

            if (!System.IO.Directory.Exists(saveDir2))
            {
                System.IO.Directory.CreateDirectory(saveDir2);
            }
            string path = string.Format("{0}test_{1}.xls",saveDir2, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss"));
            //使用文件流写入数据
            using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                
                for(int irow = 0;irow < ViewModel.mySingleROIRectList.Count();irow++)
                {
                    IRow row = sheet.CreateRow(irow);

                    MyROIRect myROIRect = ViewModel.mySingleROIRectList[irow];

                    for(int icol = 0; icol < myROIRect.LEDPoints.Count(); icol++)
                    {
                        ICell cell = row.CreateCell(icol);

                        string value = myROIRect.LEDPoints[icol].Led;

                        Console.WriteLine(value);

                        if (cell != null)
                        {
                            cell.SetCellValue(value);
                        }                
                    }

                }

                workbook.Write(fileStream);
            }
        }
        #endregion

        #region [停止测试]
        private void StopTest()
        {
            this.Loading.Show("Stopping...");

            this.FinishTest(true);
        }
        #endregion

        #region [完成测试]
        /// <summary>
        /// 完成测试
        /// </summary>
        /// <param name="isStoped">表示是否手动停止测试</param>
        private void FinishTest(bool isStoped)
        {
            //获取测试结果状态
            TestResultState result = isStoped ? TestResultState.Stop : true ? TestResultState.Pass : TestResultState.Fail;

            ViewModel.TestInfo.TestEnd(result);

            if (isStoped)
            {
                ViewModel.Status.Update("Test Stopped.", MyBrushes.Yellow);
            }
            else
            {
                ViewModel.Status.Update("Test Finished", MyBrushes.Green);

                WriteTestLog(result);
            }

            //在这里重置USB\COM等设备是否连接
            //RelayBoardHelper.Reset();

            this.ThreadSafe(() =>
            {
                this.txtBarcode.Focus();
                this.txtBarcode.SelectAll();
            }, false);

            this.Loading.Hide();

            #region 循环测试
            if (ViewModel.TestConfig.IsLoopTest)
            {
                Task.Factory.StartNew(() =>
                {
                    this.ThreadSafe(delegate
                    {
                        borderLoop.Visibility = Visibility.Visible;
                    });

                    for (int i = 0; i < ViewModel.TestConfig.LoopTestInterval; i++)
                    {
                        if (!ViewModel.TestConfig.IsLoopTest)
                        {
                            break;
                        }

                        this.ThreadSafe(delegate
                        {
                            this.txtLoopInfo.Text = string.Format("Test will start automatically after {0} seconds.", ViewModel.TestConfig.LoopTestInterval - i);
                        });

                        Thread.Sleep(TimeSpan.FromSeconds(1));
                    }

                    this.ThreadSafe(delegate
                    {
                        borderLoop.Visibility = Visibility.Collapsed;
                    });

                    if (ViewModel.TestConfig.IsLoopTest)
                    {
                        OnClick("StartTest");
                    }
                });
            }
            #endregion
        }
        #endregion

        #region 测试Log记录

        private void WriteTestLog(TestResultState result)
        {
            try
            {
                #region CSV Combine Define
                        string collectHeader = string.Format("SerialNumber,overallResult,errCode,errString,startTime,endTime,testTime");

                        string collectUpper = "UpperLimit,,,,,,";

                        string collectLower = "LowerLimit,,,,,,";

                        string errCode = "0";

                        string errString = "OK";

                        string collectData = string.Format("{0},{1},{2},{3},{4},{5},{6}",
                                                 ViewModel.TestInfo.Barcode,
                                                 result.ToString().ToUpper(),
                                                 errCode,
                                                 errString,
                                                 ViewModel.TestInfo.TestTimer.StartTime.ToString("yyyy/MM/dd HH:mm:ss"),
                                                 ViewModel.TestInfo.TestTimer.EndTime.ToString("yyyy/MM/dd HH:mm:ss"),
                                                 ViewModel.TestInfo.TestTimer.TestTime);
        #endregion

                if (!string.IsNullOrWhiteSpace(ViewModel.TestInfo.Barcode))
                {
                    string saveDir = string.Format(@"{0}TestLog\{1}\{2}\{3}\", this.GetBaseDirectory(), ViewModel.TestConfig.Project, DateTime.Now.ToString("yyyy-MM-dd"), result.ToString().ToUpper());
                    if (!System.IO.Directory.Exists(saveDir))
                    {
                        System.IO.Directory.CreateDirectory(saveDir);
                    }

                    string logFileName = saveDir + string.Format(@"{0}_{1}_{2}_{3}_{4}.csv", result.ToString().ToUpper(), ViewModel.TestInfo.Barcode, ViewModel.TestConfig.Project, ViewModel.TestConfig.Station, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));

                    string csvFileName = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(saveDir)) + string.Format(@"\Combine-{0}-{1}-{2}.csv", ViewModel.TestConfig.Project, ViewModel.TestConfig.Station, DateTime.Now.ToString("yyyy-MM-dd"));

                    bool isExists = System.IO.File.Exists(csvFileName);
                    StringBuilder sbCsv = new StringBuilder();
                    if (!isExists)
                    {
                        sbCsv.AppendLine(string.Format("{0} V{1}", this.GetAssemblyName(), this.GetVersion()));
                        sbCsv.AppendLine("Project, " + ViewModel.TestConfig.Project);
                        sbCsv.AppendLine("Station, " + ViewModel.TestConfig.Station);
                        sbCsv.AppendLine(collectHeader);
                        sbCsv.AppendLine(collectUpper);
                        sbCsv.AppendLine(collectLower);
                    }
                    sbCsv.AppendLine(collectData);
                    //sbCsv.AppendLine(collectData1);
                    //sbCsv.AppendLine(collectData2);

                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(logFileName, false, Encoding.UTF8))
                    {
                        StringBuilder sbLog = new StringBuilder();
                        sbLog.AppendLine(string.Format("{0} V{1}", this.GetAssemblyName(), this.GetVersion()));
                        sbLog.AppendLine("Project, " + ViewModel.TestConfig.Project);
                        sbLog.AppendLine("Station, " + ViewModel.TestConfig.Station);
                        sbLog.AppendLine(collectHeader);
                        sbLog.AppendLine(collectUpper);
                        sbLog.AppendLine(collectLower);
                        sbLog.AppendLine(collectData);
                        //sbLog.AppendLine(collectData1);
                        //sbLog.AppendLine(collectData2);
                        sw.Write(sbLog.ToString());
                        sw.Close();
                    }

                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(csvFileName, true, Encoding.UTF8))
                    {
                        sw.Write(sbCsv.ToString());
                        sw.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "WriteTestLog");
            }
        }

        #endregion

        #region 追加测试信息
        private Block AppendTestData(string data, MyBrushes statusBrush)
        {
            Block block = null;

            if (this.Dispatcher.Thread == System.Threading.Thread.CurrentThread)
            {
                block = GetBlock(data, statusBrush);

                this.rtxtTestData.Document.Blocks.Add(block);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    block = AppendTestData(data, statusBrush);
                });
            }

            return block;
        }

        private Block GetBlock(string data, MyBrushes statusBrush)
        {
            Inline inline = new Run(data);

            inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(statusBrush.ToBrushString()));

            return new Paragraph(inline) { LineHeight = 1.0 };
        }

        private void rtxtTestData_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.rtxtTestData.ScrollToEnd();
        }
        #endregion

        #region CheckBox Event
        private void cbCaseCode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;

            if (comboBox.SelectedValue == null)
            {
                return;
            }
            //MessageBox.Show(SelectedValue.ToString());
            Console.WriteLine("Select case :" + comboBox.SelectedValue);

            ViewModel.TestInfo.TestModelCode = (int)comboBox.SelectedValue;

            TestCodeModel testCodeModel = ViewModel.TestInfo.TestCodeModels.First(s => s.TestModelCode == (int)comboBox.SelectedValue);

            Console.WriteLine("Select case name:" + testCodeModel.Name);

            string strDefaultValue = ConfigHelper.GetVauleToString(testCodeModel.Name + "_CMDDefaultValue");

            string[] DefaultValueArr = strDefaultValue.Split(';');

            if (DefaultValueArr.Length == 23)
            {
                ViewModel.TestInfo.DvledValue =    double.Parse(DefaultValueArr[0].Trim() == "" ? "1" : DefaultValueArr[0]);
                ViewModel.TestInfo.DvLedOvpValue = double.Parse(DefaultValueArr[1].Trim() == "" ? "1" : DefaultValueArr[1]);
                ViewModel.TestInfo.DvLedOcpValue = double.Parse(DefaultValueArr[2].Trim() == "" ? "1" : DefaultValueArr[2]);
                ViewModel.TestInfo.DICOvpValue =   double.Parse(DefaultValueArr[3].Trim() == "" ? "1" : DefaultValueArr[3]);
                ViewModel.TestInfo.DICOcpValue =   double.Parse(DefaultValueArr[4].Trim() == "" ? "1" : DefaultValueArr[4]);

                ViewModel.TestInfo.IsMCSet = DefaultValueArr[5].Trim() == "" ? false : true;
                ViewModel.TestInfo.IMCValue = int.Parse(DefaultValueArr[5].Trim() == "" ? "1" : DefaultValueArr[5]);
                          
                ViewModel.TestInfo.IsDCSet = DefaultValueArr[6].Trim() == "" ? false : true;
                ViewModel.TestInfo.IsBCSet = DefaultValueArr[7].Trim() == "" ? false : true;
                          
                ViewModel.TestInfo.IDCValue = int.Parse(DefaultValueArr[6].Trim() == "" ? "1" : DefaultValueArr[6]);
                ViewModel.TestInfo.IBCValue = int.Parse(DefaultValueArr[7].Trim() == "" ? "1" : DefaultValueArr[7]);

                ViewModel.TestInfo.IsScaleSet = DefaultValueArr[8].Trim() == "" ? false : true;
                ViewModel.TestInfo.IsSRCSet = DefaultValueArr[9].Trim() == "" ? false : true;
                ViewModel.TestInfo.IsLEDNUMSet = DefaultValueArr[10].Trim() == "" ? false : true;
                ViewModel.TestInfo.IsRSETSet = DefaultValueArr[11].Trim() == "" ? false : true;
                ViewModel.TestInfo.IsCLKSet = DefaultValueArr[12].Trim() == "" ? false : true;
                          
                ViewModel.TestInfo.IScaleValue = int.Parse(DefaultValueArr[8].Trim() == "" ? "1" : DefaultValueArr[8]);
                ViewModel.TestInfo.ISrcValue = int.Parse(DefaultValueArr[9].Trim() == "" ? "1" : DefaultValueArr[9]);
                ViewModel.TestInfo.ILEDNUMValue = int.Parse(DefaultValueArr[10].Trim() == "" ? "1" : DefaultValueArr[10]);
                ViewModel.TestInfo.IRSETValue = int.Parse(DefaultValueArr[11].Trim() == "" ? "1" : DefaultValueArr[11]);
                ViewModel.TestInfo.ICLKValue = int.Parse(DefaultValueArr[12].Trim() == "" ? "1" : DefaultValueArr[12]);
                          
                ViewModel.TestInfo.IsILEDSet = DefaultValueArr[14].Trim() == "" ? false : true;
                ViewModel.TestInfo.IILEDValue = int.Parse(DefaultValueArr[14].Trim() == "" ? "1" : DefaultValueArr[14]);

                ViewModel.TestInfo.IsGCG1Set = DefaultValueArr[19].Trim() == "" ? false : true;
                ViewModel.TestInfo.IsGCG2Set = DefaultValueArr[20].Trim() == "" ? false : true;
                ViewModel.TestInfo.IsHLMSSet = DefaultValueArr[21].Trim() == "" ? false : true;
                          
                ViewModel.TestInfo.IGCG1Value = int.Parse(DefaultValueArr[19].Trim() == "" ? "1" : DefaultValueArr[19]);
                ViewModel.TestInfo.IGCG2Value = int.Parse(DefaultValueArr[20].Trim() == "" ? "1" : DefaultValueArr[20]);
                ViewModel.TestInfo.IHLMSValue = int.Parse(DefaultValueArr[21].Trim() == "" ? "1" : DefaultValueArr[21]);
                
            }

        }

        #endregion

        private bool SetModel()
        {
            #region Debug
            //AppendTestData("Debug设置", MyBrushes.Yellow);
            //if (!DLEDLightingHelper.Instance.SetDebugMode())
            //{

            //    return false;
            //}
            //else
            //{

            //    AppendTestData("Debug设置成功", MyBrushes.Green);
            //    Thread.Sleep(10);
            //}
            #endregion

            #region Model 设置
            AppendTestData("Model设置", MyBrushes.Yellow);
            if (!DLEDLightingHelper.Instance.SetCaseCode(ViewModel.TestInfo.TestModelCode))
            {

                return false;
            }
            else
            {
                
                AppendTestData("Model设置成功", MyBrushes.Green);
                Thread.Sleep(10);
            }


            if (ViewModel.TestInfo.IsVLedSet)
            {
                AppendTestData("VLED设置", MyBrushes.Yellow);

                if (!DLEDLightingHelper.Instance.SetVBL(ViewModel.TestInfo.DvledValue))
                {
                    AppendTestData("VLED设置失败", MyBrushes.Red);

                    return false;
                }
                else
                {

                    AppendTestData("VLED设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }

            }

            if (ViewModel.TestInfo.IsOCPOVPSet)
            {
                AppendTestData("过压过流设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetOCPOVP(ViewModel.TestInfo.DvLedOvpValue, ViewModel.TestInfo.DvLedOcpValue, ViewModel.TestInfo.DICOvpValue, ViewModel.TestInfo.DICOcpValue * 1000))
                {
                    AppendTestData("过压过流设置失败", MyBrushes.Red);

                    return false;
                }
                else
                {

                    AppendTestData("过压过流设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }

            if (ViewModel.TestInfo.IsMCSet)
            {
                AppendTestData("MC设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetMC(ViewModel.TestInfo.IMCValue))
                {
                    AppendTestData("MC设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("MC设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }

            if (ViewModel.TestInfo.IsDCSet)
            {
                AppendTestData("DC设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetDC(ViewModel.TestInfo.IDCValue))
                {
                    AppendTestData("DC设置失败", MyBrushes.Red);

                    return false;
                }
                else
                {
                    AppendTestData("DC设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }

            }

            if (ViewModel.TestInfo.IsBCSet)
            {
                AppendTestData("BC设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetBC(ViewModel.TestInfo.IBCValue))
                {
                    AppendTestData("BC设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("BC设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }

            if (ViewModel.TestInfo.IsScaleSet)
            {
                AppendTestData("Scale设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetSCALE(ViewModel.TestInfo.IScaleValue))
                {
                    AppendTestData("Scale设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("Scale设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }

            if (ViewModel.TestInfo.IsILEDSet)
            {
                AppendTestData("ILED设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetILED(ViewModel.TestInfo.IILEDValue))
                {
                    AppendTestData("ILED设置失败", MyBrushes.Red);

                    return false;
                }
                else
                {
                    AppendTestData("ILED设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }

            if (ViewModel.TestInfo.IsSRCSet)
            {
                AppendTestData("SRC设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetSRC(ViewModel.TestInfo.ISrcValue))
                {
                    AppendTestData("SRC设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("SRC设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }

            if (ViewModel.TestInfo.IsLEDNUMSet)
            {
                AppendTestData("LEDNUM设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetLEDNUM(ViewModel.TestInfo.ILEDNUMValue))
                {
                    AppendTestData("LEDNUM设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("LEDNUM设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }


            if (ViewModel.TestInfo.IsRSETSet)
            {
                AppendTestData("RSET设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetRSET(ViewModel.TestInfo.IRSETValue))
                {
                    AppendTestData("RSET设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("RSET设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }


            if (ViewModel.TestInfo.IsCLKSet)
            {
                AppendTestData("CLK设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetCLK(ViewModel.TestInfo.ICLKValue))
                {
                    AppendTestData("CLK设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("CLK设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }

            if (ViewModel.TestInfo.IsGCG1Set)
            {
                AppendTestData("GCG1设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetGCG1(ViewModel.TestInfo.IGCG1Value))
                {
                    AppendTestData("GCG1设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("GCG1设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }
            if (ViewModel.TestInfo.IsGCG2Set)
            {
                AppendTestData("GCG2设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetGCG2(ViewModel.TestInfo.IGCG2Value))
                {
                    AppendTestData("GCG2设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("GCG2设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }
            if (ViewModel.TestInfo.IsHLMSSet)
            {
                AppendTestData("HLMS设置", MyBrushes.Yellow);
                if (!DLEDLightingHelper.Instance.SetHLMS(ViewModel.TestInfo.IHLMSValue))
                {
                    AppendTestData("HLMS设置失败", MyBrushes.Red);
                    return false;
                }
                else
                {
                    AppendTestData("HLMS设置成功", MyBrushes.Green);
                    Thread.Sleep(10);
                }
            }
            #endregion

            return true;
        }
    }
}
